import { Dispatch, ReactNode, SetStateAction, useRef, useState } from 'react';

import { Button } from '@/shared/ui';
import cn from 'classnames';
import Image from 'next/image';
import { useIsomorphicLayoutEffect } from 'usehooks-ts';

import Minus from '../../images/icon-minus.svg';
import Plus from '../../images/icon-plus.svg';
import cs from './Dropdown.module.scss';

interface Props {
  children: ReactNode;
  title: string;
  questionNumber?: number;
  showingNumber?: number;
  setShowingNumber?: Dispatch<SetStateAction<number>>;
}

export const Dropdown = ({ children, title, questionNumber = 0, showingNumber = -2, setShowingNumber }: Props) => {
  const [active, setActive] = useState(false);
  const [isMinus, setIsMinus] = useState(false);

  const timeoutId = useRef<ReturnType<typeof setTimeout>>();
  function changeMinus(value: boolean) {
    if (value) {
      clearTimeout(timeoutId.current);
      setIsMinus(value);
    } else {
      timeoutId.current = setTimeout(() => {
        setIsMinus(value);
      }, 200);
    }
  }

  useIsomorphicLayoutEffect(() => {
    const newValue = showingNumber === questionNumber;
    changeMinus(newValue);
    setActive(newValue);
  }, [showingNumber, questionNumber]);

  function onClick() {
    if (setShowingNumber) {
      setShowingNumber((oldNumber) => (oldNumber === questionNumber ? -1 : questionNumber));
    } else {
      setActive((oldActive) => {
        changeMinus(!oldActive);
        return !oldActive;
      });
    }
  }
  return (
    <Button className={cs.wrapper} data-testid={`button-set_active-${questionNumber}`} onClick={onClick}>
      <div className={cs.flex}>
        <span className={cs.title}>{title}</span>
        <Image alt="icon" className={cs.icon} height={32} src={isMinus ? Minus : Plus} width={32} />
      </div>
      <div
        className={cn(cs.content, {
          [cs.active]: active,
        })}
      >
        {children}
      </div>
    </Button>
  );
};
